import { Button, Table, Space, Modal,Form } from 'antd';
import type { TableProps } from 'antd';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import regionMock from '@/mock/regionMock';
import '../dealership/css/region.css';

export default function Region() {
  interface DataType {
    _id: string;
    regionname: string;
    regioncode: number;
    regionkm: number;
    carnum: number;
    region_content: string;
  }

  const [data, setData] = useState<DataType[]>([]);
  const [pagesize, setPagesize] = useState(5);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isFullscreen, setIsFullscreen] = useState(false);  // Track fullscreen state
  const [isDarkMode, setIsDarkMode] = useState(false); // Track dark mode state
  const navigate = useNavigate();

  useEffect(() => {
    const savedData = localStorage.getItem('regionData');
    if (savedData) {
      setData(JSON.parse(savedData));
    } else {
      setData(regionMock);
    }
  }, []);

  // Toggle dark mode by adding/removing the 'data-theme' attribute on the <body> tag
  const handleThemeToggle = () => {
    const newMode = !isDarkMode;
    setIsDarkMode(newMode);
    if (newMode) {
      document.body.setAttribute('data-theme', 'dark');
    } else {
      document.body.removeAttribute('data-theme');
    }
  };

  const handleDelete = (_id: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个区域吗？',
      onOk: () => {
        const newData = data.filter(item => item._id !== _id);
        setData(newData);
        localStorage.setItem('regionData', JSON.stringify(newData));
      },
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      Modal.warning({
        title: '没有选中任何项',
        content: '请先选中要删除的项',
      });
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除这 ${selectedRowKeys.length} 个区域吗？`,
      onOk: () => {
        const newData = data.filter(item => !selectedRowKeys.includes(item._id));
        setData(newData);
        setSelectedRowKeys([]);
        localStorage.setItem('regionData', JSON.stringify(newData));
      },
    });
  };

  const handleEdit = (record: DataType) => {
    navigate('/addregion', { state: record });  // 传递数据到编辑页面
  };

  const handleAddNew = () => {
    navigate('/addregion');  // 跳转到新建页面
  };

  const handleFullscreen = () => {
    if (!isFullscreen) {
      if (document.documentElement.requestFullscreen) {
        document.documentElement.requestFullscreen();
      } else if (document.documentElement.mozRequestFullScreen) {
        document.documentElement.mozRequestFullScreen();
      } else if (document.documentElement.webkitRequestFullscreen) {
        document.documentElement.webkitRequestFullscreen();
      } else if (document.documentElement.msRequestFullscreen) {
        document.documentElement.msRequestFullscreen();
      }
      setIsFullscreen(true);
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) { 
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) { 
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
      setIsFullscreen(false);
    }
  };

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '区域名称',
      dataIndex: 'regionname',
      key: 'regionname',
      width: '200px',
      align: 'center',
    },
    {
      title: '区域编号',
      dataIndex: 'regioncode',
      key: 'regioncode',
      width: '200px',
      align: 'center',
    },
    {
      title: '面积',
      dataIndex: 'regionkm',
      key: 'regionkm',
      width: '200px',
      align: 'center',
    },
    {
      title: '车位数量',
      dataIndex: 'carnum',
      key: 'carnum',
      width: '200px',
      align: 'center',
    },
    {
      title: '备注',
      dataIndex: 'region_content',
      key: 'region_content',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <a onClick={() => handleDelete(record._id)}>删除</a>
        </Space>
      ),
      width: '250px',
      align: 'center',
    },
  ];

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  return (
    <div className="region">
      <div className="region-title">
        <p className="region-text">区域列表</p>
        <div className="region-btn">
          <Button type="primary" style={{ marginTop: '10px' }} onClick={handleAddNew}>
            +新建
          </Button>
          <Button
            type="default"
            style={{ marginTop: '10px', marginLeft: '30px' }}
            onClick={handleBatchDelete}
          >
            批量删除
          </Button>
          <Button
            type="default"
            style={{ marginTop: '10px', marginLeft: '30px' }}
            onClick={handleFullscreen}
          >
            {isFullscreen ? '退出全屏' : '全屏'}
          </Button>
          <Button
            type="default"
            style={{ marginTop: '10px', marginLeft: '30px' }}
            onClick={handleThemeToggle}
          >
            {isDarkMode ? '切换到亮色模式' : '切换到暗黑模式'}
          </Button>
        </div>
      </div>
      <div className="region-table" style={{ marginTop: '20px', marginLeft: '20px' }}>
        <Table<DataType>
          rowSelection={{
            type: 'checkbox',
            onChange: onSelectChange,
            selectedRowKeys,
          }}
          columns={columns}
          dataSource={data}
          rowKey="_id"
          pagination={{
            position: ['bottomCenter'],
            pageSize: pagesize,
            total: data.length,
            showSizeChanger: true,
            pageSizeOptions: ['3', '5', '7', '9'],
            onShowSizeChange: (current, pageSize) => { setPagesize(pageSize); },
          }}
        />
      </div>
    </div>
  );}
